package com.sp.fresh_produce.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sp.fresh_produce.common.Constant;
import com.sp.fresh_produce.controller.dto.VO.CategoryVORequest;
import com.sp.fresh_produce.controller.dto.req.ProductListReq;
import com.sp.fresh_produce.controller.dto.req.ProductRequest;
import com.sp.fresh_produce.ex.CustomException;
import com.sp.fresh_produce.ex.ExceptionCodeEnum;
import com.sp.fresh_produce.model.dao.ProductMapper;
import com.sp.fresh_produce.model.pojo.Order;
import com.sp.fresh_produce.model.pojo.Product;
import com.sp.fresh_produce.model.query.ProductListQuery;
import com.sp.fresh_produce.service.AdminProduceService;
import com.sp.fresh_produce.service.CategoryService;
import com.sp.fresh_produce.util.PageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminProductServiceImpl implements AdminProduceService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryService categoryService;

    /**
     * 添加商品
     *
     * @param productRequest
     * @return
     */
    @Override
    public int addProduct(ProductRequest productRequest) {
        Product product = new Product();
        BeanUtils.copyProperties(productRequest, product);
        // 查看是否存在相同名称的商品
        Product productOld = productMapper.selectByName(product.getName());
        if (productOld != null) {
            throw new CustomException(ExceptionCodeEnum.PRODUCT_NAME_EXIST.getCode(), ExceptionCodeEnum.PRODUCT_NAME_EXIST.getMessage());
        }
        int result = productMapper.insertSelective(product);
        if (result == 0) {
            throw new CustomException(ExceptionCodeEnum.PRODUCT_ADD_ERROR.getCode(), ExceptionCodeEnum.PRODUCT_ADD_ERROR.getMessage());
        }
        return result;
    }

    /**
     * 修改商品信息
     *
     * @param product
     * @return
     */
    @Override
    public void updateProduct(Product product) {
        Product productOld = productMapper.selectByName(product.getName());
        if (productOld != null && productOld.getId().equals(product.getId())) {
            throw new CustomException(ExceptionCodeEnum.PRODUCT_NAME_EXIST.getCode(), ExceptionCodeEnum.PRODUCT_NAME_EXIST.getMessage());
        }
        int result = productMapper.updateByPrimaryKeySelective(product);
        if (result == 0) {
            throw new CustomException(ExceptionCodeEnum.PRODUCT_UPDATE_ERROR.getCode(), ExceptionCodeEnum.PRODUCT_UPDATE_ERROR.getMessage());
        }
    }

    /**
     * 删除商品
     */
    @Override
    public void deleteProduct(Integer id) {
        Product product = productMapper.selectByPrimaryKey(id);
        if (product == null) {
            throw new CustomException(ExceptionCodeEnum.PRODUCT_NOT_EXIST.getCode(), ExceptionCodeEnum.PRODUCT_NOT_EXIST.getMessage());
        }
        int result = productMapper.deleteByPrimaryKey(id);
        if (result == 0) {
            throw new CustomException(ExceptionCodeEnum.PRODUCT_DELETE_ERROR.getCode(), ExceptionCodeEnum.PRODUCT_DELETE_ERROR.getMessage());
        }
    }

    /**
     * 批量上下架商品
     *
     * @param ids
     * @param sellStatus
     */
    @Override
    public void batchUpdateProductStatus(Integer[] ids, Integer sellStatus) {
        int result = productMapper.batchUpdateProductStatus(ids, sellStatus);
        if (result == 0) {
            throw new CustomException(ExceptionCodeEnum.PRODUCT_UPDATE_ERROR.getCode(), ExceptionCodeEnum.PRODUCT_UPDATE_ERROR.getMessage());
        }
    }

    /**
     * 商品列表
     */
    @Override
    public PageInfo<Product> getProductList(Integer pageNum, Integer pageSize) {
        // 使用工具类规范化分页参数
        int[] pageParams = PageUtil.normalizePagination(pageNum, pageSize);
        int safePageNum = pageParams[0];
        int safePageSize = pageParams[1];
        
        // 计算偏移量并查询数据
        int offset = PageUtil.calculateOffset(safePageNum, safePageSize);
        List<Product> pageList = productMapper.selectProductPage(offset, safePageSize);
        int total = productMapper.countProductAll();
        
        // 使用工具类构建分页信息
        return PageUtil.buildPageInfo(pageList, total, safePageNum, safePageSize);
    }

    /**
     * 商品详情
     */
    @Override
    public Product getProductDetail(Integer id) {
        Product product = productMapper.selectByPrimaryKey(id);
        if (product == null) {
            throw new CustomException(ExceptionCodeEnum.PRODUCT_NOT_EXIST.getCode(), ExceptionCodeEnum.PRODUCT_NOT_EXIST.getMessage());
        }
        return product;
    }

    /**
     * 商品列表
     */
    @Override
    public PageInfo list(ProductListReq productListReq) {
        // 创建查询参数对象
        ProductListQuery productListQuery = new ProductListQuery();
        // 搜索关键字
        if (!StringUtils.isEmpty(productListReq.getKeyword())) {
            String keyword = new StringBuilder().append("%").append(productListReq.getKeyword()).append("%").toString();
            productListQuery.setKeyword(keyword);
        }

        // 获取分类列表，如果 categoryId 为 null，则获取所有分类
        Integer categoryId = productListReq.getCategoryId();
        List<CategoryVORequest> categoryListForUser = categoryService.getCategoryListForUser(categoryId);

        // 收集所有子分类ID
        ArrayList<Integer> list = new ArrayList<>();
        // 如果 categoryId 为 null，不需要添加特定分类ID，否则添加当前分类ID
        if (categoryId != null) {
            list.add(categoryId);
        }
        getCategoryIds(categoryListForUser, list);
        productListQuery.setCategoryIds(list);

        String orderBy = productListReq.getOrderBy();
        String pageHelperOrderBy;
        if (orderBy != null && Constant.ProductListOrderBy.ALL_SORT_RULES.contains(orderBy)) {
            // 将排序参数转换为 PageHelper 可识别的格式
            pageHelperOrderBy = convertToPageHelperOrderBy(orderBy);
        } else {
            // 默认按更新时间降序
            pageHelperOrderBy = "update_time desc";
        }
        PageHelper.startPage(productListReq.getPageNum(), productListReq.getPageSize(), pageHelperOrderBy);
        List<Product> products = productMapper.selectList(productListQuery);
        return new PageInfo(products);
    }

    private void getCategoryIds(List<CategoryVORequest> categoryList, List<Integer> categoryIds) {
        for (int i = 0; i < categoryList.size(); i++) {
            CategoryVORequest categoryVORequest = categoryList.get(i);
            if (categoryVORequest != null) {
                categoryIds.add(categoryVORequest.getId());
                getCategoryIds(categoryVORequest.getChildren(), categoryIds);
            }
        }
    }

    /**
     * 将前端的排序参数转换为 PageHelper 可识别的排序格式
     * 
     * @param orderBy 前端传入的排序参数，如 "price_asc", "price_desc" 等
     * @return PageHelper 可识别的排序格式，如 "price asc", "price desc" 等
     */
    private String convertToPageHelperOrderBy(String orderBy) {
        if (orderBy == null || orderBy.isEmpty()) {
            return null;
        }
        
        // 将下划线分隔的排序参数转换为空格分隔
        // 例如: "price_asc" -> "price asc", "name_desc" -> "name desc"
        String result = orderBy.replace("_", " ");
        
        // 处理特殊字段名称映射（如果有需要）
        // 这里可以添加对特殊字段的处理逻辑
        
        return result;
    }
}
